#!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
项目名称: 中青晶彩看点查询分享奖励
Author: Fidcz
功能: 中青晶彩看点查询分享奖励
Date: 2021/12/03 15:17
Update: 2021/12/20 21:21
cron: 0 50 22 * * ?
new Env('中青晶彩看点查询分享奖励');

    中青cookie保存为 export zq_cookies="cookie1:备注1@cookie2:备注2" # 备注可忽略 "cookie1@cookie2"
    晶彩cookie为 jc_cookies,其他同上
"""

import time
# from urllib.parse import urlencode
import requests
import json
import sys, os
from datetime import datetime, timedelta
import logging

# 使用logger输出
logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger(__name__)

def loadSend():
    #print("加载推送功能")
    global send
    send = None
    cur_path = os.path.abspath(os.path.dirname(__file__))
    sys.path.append(cur_path)
    if os.path.exists(cur_path + "/sendNotify.py"):
        try:
            from sendNotify import send
        except Exception as e:
            send = None
            print("加载通知服务失败~",e)


def bodyTodict(bodyString):
    """
        把body形式文本转为dict
    """

    temp_split = bodyString.split('&')

    resultDict= {}
    for data in temp_split:
        resultDict[data.split('=')[0]] = data.split('=')[1]
    
    # print(resultDict)
    return resultDict

def getZqCookie():
    """
        获取中青cookie,返回list
    """
    cookieList = []
    if 'zq_cookies' in os.environ:
        cookiesStr = os.environ["zq_cookies"]
        # 使用@分割每个cookie
        cookiesSplit = cookiesStr.split('@')
        for cookie in cookiesSplit:
            if ':' in cookie:
                cookieList.append([cookie.split(':')[0], cookie.split(':')[1]])
            else:
                cookieList.append([cookie.split(':')[0], ''])

    return cookieList

def getJcCookie():
    """
        获取晶彩cookie,返回list
    """
    cookieList = []
    if 'jc_cookies' in os.environ:
        cookiesStr = os.environ["jc_cookies"]
        # 使用@分割每个cookie
        cookiesSplit = cookiesStr.split('@')
        for cookie in cookiesSplit:
            if ':' in cookie:
                cookieList.append([cookie.split(':')[0], cookie.split(':')[1]])
            else:
                cookieList.append([cookie.split(':')[0], ''])

    return cookieList


def getShareRecord(pt:str='zq', cookie:str='', dateDay:int=5, limitCount:int=4):
    """
        获取中青分享奖励
    """
    try:
        domain = 'kandian.wkandian.com'
        jlText = '青豆'
        if pt == 'jc':
            domain = 'ant.xunsl.com'
            jlText = '金币'

        if cookie == '' or cookie == None:
            return []

        if dateDay <= 0:
            dateDay = 3

        shareRecordList = []

        time1 = int(time.time())
        # uid = cookie.split('&uid=')[1]
        bodyVal = cookie.split('&uid')[0]
        cookie1 = bodyVal.replace('zqkey=', 'cookie=')
        cookie_id = cookie1.replace('zqkey_id=', 'cookie_id=')

        zq_cookie1 = f'{cookie_id}&device_brand=xfdg&device_id=cc7dgdsgfsz83e&device_model=1gx&device_platform=android&device_type=android&inner_version=202107261526&mi=0&openudid=cc7dgdsgfsz83e&os_api=27&os_version=bdftgsdfga&phone_network=WIFI&phone_sim=1&request_time={str(time1)}&time={str(time1-10)}&{bodyVal}'

        getJlUrl = f'https://{domain}/WebApi/ArticleTop2/getShareRecord'
        getJlHeader = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': str(len(zq_cookie1)),
            'Host': domain,
            'Referer': f'https://{domain}/h5/20200612makeMoney/?' + zq_cookie1
        }

        getJlData = zq_cookie1
        getJlRespon = requests.post(url=getJlUrl, headers=getJlHeader, data=bodyTodict(getJlData))
        # print(getJlRespon.text)
        # with open('test.json', 'w') as file:
        #     file.write(json.dumps(getJlRespon.json(), ensure_ascii=False))
        getJlRespon = getJlRespon.json()
        if int(getJlRespon['status']) != 1:
            return [[getJlRespon['msg']]]

        dayIndex = 1
        for (key, value) in getJlRespon['data'].items():
            try:
                dayIndex += 1
                if len(value) <= 0:
                    continue

                # 开始获取结果
                for dataIndex in range(len(value)):
                    if int(value[dataIndex]['read_num']) != 0 or int(value[dataIndex]['score']) != 0:
                        shareRecordList.append([
                            f'标题:{value[dataIndex]["article"]["title"]}', 
                            f'分享时间:{value[dataIndex]["date_time"]}',
                            f'阅读人数:{value[dataIndex]["read_num"]}人',
                            f'获得奖励:{value[dataIndex]["score"]}{jlText}']
                            )

            except Exception as error2:
                shareRecordList.append([f'获取出错:{repr(error2)}', f'error line:{error2.__traceback__.tb_lineno}'])
            finally:
                if dayIndex >= dateDay:
                    break
                if len(shareRecordList) >= limitCount:
                    break
        # for dayIndex in range(dateDay):
    except Exception as error:
        return [[f'获取出错:{repr(error)}', f'error line:{error.__traceback__.tb_lineno}']]
    
    return shareRecordList

if __name__ == '__main__':
    zq_cookies = jc_cookies = []
    zq_cookies = getZqCookie()
    jc_cookies = getJcCookie()
    logger.info(f'提供了{len(zq_cookies)}个中青账号')
    logger.info(f'提供了{len(jc_cookies)}个晶彩账号')

    if len(zq_cookies) == 0 and len(jc_cookies) == 0:
        logger.info('\n未提供中青或晶彩cookie,结束')

    loadSend()
    sendList = []

    logger.info('\n>>>>开始获取中青分享奖励<<<<')

    for zq_cookie_index in range(len(zq_cookies)):
        shareRecordList = getShareRecord('zq', zq_cookies[zq_cookie_index][0])

        logger.info(f'\n\n>>中青账号{zq_cookie_index+1}:{zq_cookies[zq_cookie_index][1]} 分享奖励如下:')
        tempSendText = f'\n\n>>中青账号{zq_cookie_index+1}:{zq_cookies[zq_cookie_index][1]} 分享奖励如下:'
        if len(shareRecordList) <= 0:
            logger.info('无')
            tempSendText += '无'
            sendList.append(tempSendText)
            continue
        for shareRecord in shareRecordList:
            for shareIndex in shareRecord:
                logger.info(f'   {shareIndex}')
                tempSendText += f'\n   {shareIndex}'
            logger.info('\n')
            tempSendText += '\n'
        
        sendList.append(tempSendText)

    logger.info('\n\n>>>>开始获取晶彩分享奖励<<<<')

    for jc_cookie_index in range(len(jc_cookies)):
        shareRecordList = getShareRecord('jc', jc_cookies[jc_cookie_index][0])

        logger.info(f'\n>>晶彩账号{jc_cookie_index+1}:{jc_cookies[jc_cookie_index][1]} 分享奖励如下:')
        tempSendText = f'\n>>晶彩账号{jc_cookie_index+1}:{jc_cookies[jc_cookie_index][1]} 分享奖励如下:'
        if len(shareRecordList) <= 0:
            logger.info('无')
            tempSendText += '无'
            sendList.append(tempSendText)
            continue
        for shareRecord in shareRecordList:
            for shareIndex in shareRecord:
                logger.info(f'   {shareIndex}')
                tempSendText += f'\n   {shareIndex}'
            logger.info('\n')
            tempSendText += '\n'
        
        sendList.append(tempSendText)
    
    if send:
        if len(sendList) > 0:
            sendText = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            sendText += (''.join(sendList))[1:]
            send('中青晶彩分享奖励', sendText)
    exit(1)